package com.cherry.androidcode.main.provider

import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cherry.androidcode.R
import com.cherry.androidcode.entity.MallHome
import com.cherry.androidcode.entity.MallHomeMultiple
import com.cherry.androidcode.helper.DrawableHelper
import com.cherry.androidcode.recyclerView.QuickViewHolder
import com.cherry.androidcode.util.dpToPx
import com.cherry.androidcode.util.inflate
import com.parkingwang.android.SwToast

/**
 * @author DongMS
 * @since 2019/7/16
 */
class MainTopClassProvider : AbsBaseItemProvider<MallHomeMultiple<*>>() {

    override val layoutId: Int = R.layout.holder_class

    override val itemViewType: Int = MallHomeMultiple.CLASS_PRODUCT


    private val viewList = arrayListOf<View>()

    override fun initView(helper: BaseViewHolder, data: MallHomeMultiple<*>, position: Int) {
        //这里viewpager需要指定高度，否则无法显示
        helper.getView<ViewPager>(R.id.viewPager).apply {
            adapter = object : PagerAdapter() {
                override fun isViewFromObject(view: View, `object`: Any) = view == `object`

                override fun getCount() = pageCount(data.list)

                override fun instantiateItem(container: ViewGroup, position: Int): Any {
                    return viewList[position].apply {
                        container.addView(this)
                    }
                }

                override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                    container.removeView(`object` as View)
                }
            }
            addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
                override fun onPageSelected(position: Int) {
                    val llIndicator = helper.getView<LinearLayout>(R.id.ll_indicator)
                    for (i in 0 until llIndicator.childCount) {
                        llIndicator.getChildAt(i).isSelected = i == position
                    }
                }
            })
        }
    }


    override fun bindDataToViewHolder(helper: BaseViewHolder, data: MallHomeMultiple<*>, position: Int) {
        Log.e("-------", "有脏数据或者刷新")

        val pageCount = pageCount(data.list)

        //设置指示器
        val llIndicator = helper.getView<LinearLayout>(R.id.ll_indicator)
        viewList.clear()
        llIndicator.removeAllViews()
        for (i in 0 until pageCount) {
            val childRecyclerView = R.layout.layout_recycler_view.inflate(context = context) as RecyclerView
            childRecyclerView.layoutManager = GridLayoutManager(context, COLUMN)
            val endSubIndex = if (i != pageCount - 1) {
                (i + 1) * PAGE_SIZE
            } else {
                data.list?.size ?: 0
            }
            val subDataList: MutableList<MallHome.ClassData>? = data.list?.subList(i * PAGE_SIZE, endSubIndex)?.map {
                it as MallHome.ClassData
            }?.toMutableList()
            object : BaseQuickAdapter<MallHome.ClassData, QuickViewHolder>(R.layout.item_class, subDataList) {
                override fun convert(helper: QuickViewHolder, item: MallHome.ClassData) {
                    helper.setImageWithGlide(R.id.iv, item.imgUrl)
                            .setText(R.id.text, item.title)
                }
            }.apply {
                childRecyclerView.adapter = this
                setOnItemClickListener { _, _, position ->
                    SwToast.showShort((data.list?.get(position)
                            as? MallHome.ClassData)?.title ?: "")
                }
            }

            viewList.add(childRecyclerView)
            val view = View(context)
            view.background = DrawableHelper.pointIndicatorDrawable()
            val params = LinearLayout.LayoutParams(5f.dpToPx(), 5f.dpToPx())
            if (i > 0) {
                params.leftMargin = 5f.dpToPx()
            } else {
                view.isSelected = true
            }
            llIndicator.addView(view, params)
        }
        if (!isFirstInit) {
            helper.getView<ViewPager>(R.id.viewPager).adapter?.notifyDataSetChanged()
        }
    }

    private fun pageCount(data: List<*>?): Int {
        return (data?.size ?: 0).let {
            if (it % PAGE_SIZE == 0) {
                it / PAGE_SIZE
            } else {
                it / PAGE_SIZE + 1
            }
        }
    }

    companion object {
        const val PAGE_SIZE = 8  //每页8个元素
        const val COLUMN = 4  //列
    }

}